package com.quickdv.network;

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.quickdv.activity.BaseApplication;
import com.quickdv.helper.imp.NetWorkInfo;
import com.quickdv.network.request.FastRequest;
import com.quickdv.until.LogHelper;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lilongfei on 15/5/1.
 */
public class HttpConnect {

    NetWorkInfo responseListener;
    String url = BaseApplication.properties.getProperty("url");
    RequestQueue mRequestQueue;
    Context context;
    LogHelper helper = LogHelper.getInstance();
    private final int MY_SOCKET_TIMEOUT_MS = 10000;

    public HttpConnect(Context context, NetWorkInfo responseListener) {
        this.mRequestQueue = Volley.newRequestQueue(context);
        this.context = context;
        this.responseListener = responseListener;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * fastjson
     */
    public void addToRequestQueue(int type, final Object tag, String methods, com.alibaba.fastjson.JSONObject params) {

        helper.v(tag.toString(), params.toString());
        final FastRequest requested = new FastRequest(type, url, params, new Response.Listener<com.alibaba.fastjson.JSONObject>() {

            @Override
            public void onResponse(com.alibaba.fastjson.JSONObject response) {

                try {
                    responseListener.onFastJsonResponse(tag, response);
                } catch (Exception e) {
                    helper.v("网络请求输出异常", e.toString());
                    helper.v("异常信息如下", e.getMessage() != null ? e.getMessage() : "NullPointer");
                    helper.v("输出位置", Thread.class.getClass().getName());
                    responseListener.onErrorResponse(new VolleyError());
                }
            }


        }, responseListener) {
            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("Accept", "application/json");
                headers.put("Content-Type", "application/json; charset=UTF-8");

                return headers;
            }


        };


        requested.setTag(tag);
        requested.setRetryPolicy(new DefaultRetryPolicy(
                MY_SOCKET_TIMEOUT_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mRequestQueue.add(requested);
    }

    public void start() {
        mRequestQueue.start();
    }

    public void stopRequest() {
        if (mRequestQueue != null)
            mRequestQueue.cancelAll(context);
    }
}
